﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using HSE.Common;
using Microsoft.Practices.Prism.Modularity;
using Telerik.Windows.Controls;
using PetroMentor.Service.Common;
using PetroMentor.Service;
using PetroMentor.Service.Entities;
using Newtonsoft.Json;

namespace PetroMentor
{
    public partial class App : Application
    {

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();

            StyleManager.ApplicationTheme = new MetroTheme();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            SystemVar.ServiceUrl = e.InitParams["ServiceUrl"];
            InitModule();
            
        }

        public void InitModule()
        {
            WebClient web = new WebClient();
            Uri endpoint = new Uri(String.Format("{0}QueryHanlder.ashx?{1}={2}&{3}={4}&{5}={6}&{7}={8}&{9}={10}", SystemVar.ServiceUrl,
                Consts.MODULE, typeof(T_CFG_MODULE).Name, Consts.PAGE_NUMBER, 1, Consts.PAGE_SIZE, 500, Consts.WHERE, "", Consts.ORDERBY," ORDERFLAG asc"));

            web.DownloadStringCompleted += new DownloadStringCompletedEventHandler(web_DownloadStringCompleted);
            web.DownloadStringAsync(endpoint);
        }

        void web_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    SystemVar.SysInfoCollection = new List<SysInfo>();
                    CommonQueryInfo<T_CFG_MODULE> info = JsonConvert.DeserializeObject<CommonQueryInfo<T_CFG_MODULE>>(e.Result);
                   
                    List<List<T_CFG_MODULE>> l = new List<List<T_CFG_MODULE>>();
                    l.Add(info.ResultInfos.Where(item => item.SYSTEMID == "01").ToList());
                    l.Add(info.ResultInfos.Where(item => item.SYSTEMID == "02").ToList());
                    SystemVar.PADMODULE = info.ResultInfos.Where(item => item.SYSTEMID == "03").ToList();
                    //l.Add();
                    SystemVar.SysInfoCollection.Add(new SysInfo { SysID = "01", Functions = new System.Collections.ObjectModel.ObservableCollection<ToolBarNaviInfo>() });
                    SystemVar.SysInfoCollection.Add(new SysInfo { SysID = "02", Functions = new System.Collections.ObjectModel.ObservableCollection<ToolBarNaviInfo>() });
                    foreach (List<T_CFG_MODULE> modules in l)
                    {
                       List<T_CFG_MODULE> rootmodules = modules.Where(item => string.IsNullOrWhiteSpace(item.PID)).ToList();
                       foreach (T_CFG_MODULE m in rootmodules)
                       {
                           if(m.SYSTEMID == "01")
                               SystemVar.SysInfoCollection[0].Functions.Add(GetToolBarNaviInfo(m, modules));
                           else if(m.SYSTEMID == "02")
                               SystemVar.SysInfoCollection[1].Functions.Add(GetToolBarNaviInfo(m, modules));
                       }
                    }

                    HSEBootstrapper bootstrapper = new HSEBootstrapper();

                    bootstrapper.Run();
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(string.Format("获取系统模块发生异常！{0}", ex.Message));
            }
        }

        ToolBarNaviInfo GetToolBarNaviInfo(T_CFG_MODULE rootmodules, List<T_CFG_MODULE> modules)
        {
            ToolBarNaviInfo info = new ToolBarNaviInfo();
            info.Init(rootmodules);

           List<T_CFG_MODULE> sub =  modules.Where(item => item.PID == rootmodules.ID).ToList();
           foreach (T_CFG_MODULE m in sub)
           {
               info.SubItems.Add(GetToolBarNaviInfo(m, modules));
           }

            return info;
            
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // 如果应用程序是在调试器外运行的，则使用浏览器的
            // 异常机制报告该异常。在 IE 上，将在状态栏中用一个 
            // 黄色警报图标来显示该异常，而 Firefox 则会显示一个脚本错误。
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // 注意: 这使应用程序可以在已引发异常但尚未处理该异常的情况下
                // 继续运行。 
                // 对于生产应用程序，此错误处理应替换为向网站报告错误
                // 并停止应用程序。
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}
